﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Yz.Core.Tools;

namespace Yz.Core.Extensions
{
    public static class ImageExtension
    {
        /// <summary>
        /// 图片转为base64编码的字符串
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string GetBase64String(this string filename)
        {
            try
            {
                var bmp = new Bitmap(filename);
                var ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);
                var arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                YzNLog.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// base64编码的字符串转为图片
        /// </summary>
        /// <param name="strbase64"></param>
        /// <param name="imagePath"></param>
        /// <param name="imgFormat"></param>
        /// <returns></returns>
        public static Bitmap Base64StringToImage(this string base64, string imagePath, ImageFormat imgFormat)
        {
            try
            {
                var arr = Convert.FromBase64String(base64);
                var ms = new MemoryStream(arr);
                var bmp = new Bitmap(ms);
                bmp.Save(imagePath, imgFormat);
                ms.Close();
                return bmp;
            }
            catch (Exception ex)
            {
                YzNLog.Error(ex);
                return null;
            }
        }

        /// <summary>
        ///     把base64字符串转换成image对象
        /// </summary>
        /// <param name="strBase64"></param>
        /// <returns></returns>
        public static Image Base64StrToImage(this string base64)
        {
            var bytes = Convert.FromBase64String(base64);
            var memStream = new MemoryStream(bytes);
            var bmp = new Bitmap(memStream);
            return bmp;
        }
        /// <summary>
        ///  把base64字符串转换成 byte[]
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static byte[] Base64StrToByte(this string base64)
        {
            var bytes = Convert.FromBase64String(base64);
            return bytes;
        }
    }
}
